﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextMining;

namespace HierarchicalClustering.LinkageCriteria
{
    public class Average : ILinkage
    {
        #region ILinkage Members

        public double Distance(Cluster clusterA, Cluster clusterB, HierarchicalClustering.Metrics.IMetric metric)
        {   // SSd(a,b)
            double sum = 0.0;

            // the distance between 2 clusters is the summary of the distances between their documents

            foreach (Document docA in clusterA.Documents)
            {
                foreach (Document docB in clusterB.Documents)
                {
                    sum += metric.Distance(docA, docB);
                }                
            }

            return sum;
        }

        public double AddWeight(Cluster clusterA, Cluster clusterB, double distance)
        {
            // (1 / |A| * |B|) * SSd(a,b)
            
            return distance / (clusterA.Documents.Count * clusterB.Documents.Count);
        }

        public double NewDistance(double distanceA, double distanceB)
        {
            // SSd(a,b) = SSd(a1,b1) + SSd(a2,b2)

            return distanceA + distanceB;
        }

        #endregion
    }
}
